<template>
	<view>
		<uni-popup ref='popup' :type='type' :safe-area="safeArea" :isMaskClick="isMaskClick" @change='changeHandler'>
			<slot></slot>
		</uni-popup>
	</view>
</template>

<script setup lang="ts">

withDefaults(defineProps<{
	type: 'top' | 'center' | 'bottom' | 'left' | 'right' | 'dialog',//弹出层类型
	safeArea: boolean,
	isMaskClick: boolean,
}>(), {
	type: 'bottom',
	safeArea: false,
	isMaskClick: true
});

interface EmitType {
	(e: 'open'): void,
	(e: 'close'): void,
	(e: 'change', show: boolean): void
}
const emits = defineEmits<EmitType>();
let hasTriggerChange = false; //防止调用close时多次触发change

interface Popup {
	close: () => void,
	open: () => void
}
const popup = ref<Popup>();

const isOpened = ref(false);

const open = () => {
	hasTriggerChange = false;
	isOpened.value = true;
	popup.value?.open();
};

const close = () => {
	hasTriggerChange = true;//手动调用close，只触发一次change，避免调用栈溢出
	isOpened.value = false;
	popup.value?.close();
};

const changeHandler = (e: { show: boolean }) => {
	isOpened.value = e.show;
	!hasTriggerChange && emits('change', e.show);
};

defineExpose({
	open,
	close,
	isOpened
});

</script>

<style scoped lang="less"></style>